package com.huan;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author chenbin78
 * @version 1.0
 * @create_date 2021/4/19 11:12
 */
public class AtomicIntegerTest {


    private Map<Integer, Integer> map = new HashMap<>();

    private int count = 1;

    //0表示线程0可以执行, 1表示线程1可以执行
    AtomicInteger atomicInteger = new AtomicInteger(0);

    public void put() {
        for (int i = 0; i < 10; i++) {
            //自旋
            for (;;) {
                if ((atomicInteger.intValue() & 1) == 0) {
                    break;
                }
            }
            map.put(count, count);
            System.out.println(Thread.currentThread().getName() + "put：" + count);
            count ++ ;
            atomicInteger.compareAndSet(atomicInteger.intValue(), 1);
        }
        System.out.println(Thread.currentThread().getName() + "执行完毕！");
    }

    public void get() {
        for (int i = 0; i < 10; i++) {
            //自旋
            for (;;) {
                if ((atomicInteger.intValue() & 1) == 1) {
                    break;
                }
            }
            Integer integer = map.get(count - 1);
            System.out.println(Thread.currentThread().getName() + " get：" + integer);
            atomicInteger.compareAndSet(atomicInteger.intValue(), 0);
        }
        System.out.println(Thread.currentThread().getName() + "执行完毕！");
    }
}
